package com.feiyangedu.sample;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

public class TCPServer {

    public static void main(String[] args) throws  Exception{
        @SuppressWarnings("resource")
        ServerSocket ss = new ServerSocket(9090);
        System.out.println("TCP Server Start");
        for(;;){
            Socket socket = ss.accept();
            System.out.println("Accept from " + socket.getRemoteSocketAddress());
            TimeHandler handler = new TimeHandler(socket);
            handler.start();
        }

    }
}

class TimeHandler extends  Thread{
    Socket socket;
    TimeHandler(Socket socket){
        this.socket = socket;
    }


    @Override
    public void run() {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                socket.getInputStream(), StandardCharsets.UTF_8
        ))){
            try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                    socket.getOutputStream(), StandardCharsets.UTF_8
            ))){
                for(;;){
                    String cmd = reader.readLine();
                    if("q".equals(cmd)){
                        writer.write("Bye! \n");
                        writer.flush();
                        break;
                    }else if ("time".equals(cmd)){
                        writer.write(LocalDateTime.now().toString() + "\n");
                        writer.flush();
                    }else {
                        writer.write("Sorry?\n");
                        writer.flush();
                    }
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                this.socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
